<?php
require_once '../../config/database.php';
require_once '../../utils/Database.php';
require_once '../../utils/WeChatAuth.php';
require_once '../../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 检查管理员权限
function checkAdminPermission($requiredPermission = null) {
    global $auth, $db;
    $user = $auth->getCurrentUser();
    if (!$user) {
        Response::authError('请先登录');
    }
    
    // 检查是否为管理员
    $adminUser = $db->fetchOne("
        SELECT au.*, ar.permissions, ar.role_code 
        FROM admin_users au 
        JOIN admin_roles ar ON au.role_id = ar.id 
        WHERE au.user_id = ? AND au.is_active = 1 AND ar.is_active = 1
    ", [$user['id']]);
    
    if (!$adminUser) {
        Response::error('权限不足');
    }
    
    // 检查具体权限
    if ($requiredPermission) {
        $permissions = json_decode($adminUser['permissions'], true);
        if (!in_array('*', $permissions) && !in_array($requiredPermission, $permissions)) {
            // 检查模块权限（如 admin.*）
            $modulePermission = explode('.', $requiredPermission)[0] . '.*';
            if (!in_array($modulePermission, $permissions)) {
                Response::error('权限不足');
            }
        }
    }
    
    return $adminUser;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'roles':
                // 获取角色列表
                $admin = checkAdminPermission('admin.view');
                
                $roles = $db->fetchAll("
                    SELECT ar.*, 
                           COUNT(au.id) as admin_count
                    FROM admin_roles ar
                    LEFT JOIN admin_users au ON ar.id = au.role_id AND au.is_active = 1
                    WHERE ar.is_active = 1
                    GROUP BY ar.id
                    ORDER BY ar.created_at
                ");
                
                // 解析权限JSON
                foreach ($roles as &$role) {
                    $role['permissions'] = json_decode($role['permissions'], true);
                }
                
                Response::success($roles, '获取成功');
                break;
                
            case 'admins':
                // 获取管理员列表
                $admin = checkAdminPermission('admin.view');
                
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 20);
                $search = $_GET['search'] ?? '';
                $roleId = $_GET['role_id'] ?? '';
                $offset = ($page - 1) * $limit;
                
                $whereConditions = ['au.is_active = 1'];
                $params = [];
                
                if ($search) {
                    $whereConditions[] = "(au.admin_name LIKE ? OR au.admin_phone LIKE ? OR au.admin_email LIKE ? OR u.nickname LIKE ?)";
                    $searchTerm = "%{$search}%";
                    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
                }
                
                if ($roleId) {
                    $whereConditions[] = "au.role_id = ?";
                    $params[] = $roleId;
                }
                
                $whereClause = 'WHERE ' . implode(' AND ', $whereConditions);
                
                // 获取管理员列表
                $admins = $db->fetchAll("
                    SELECT au.*, u.nickname, u.phone as user_phone, u.avatar_url, u.openid,
                           ar.role_name, ar.role_code, ar.permissions
                    FROM admin_users au
                    JOIN users u ON au.user_id = u.id
                    JOIN admin_roles ar ON au.role_id = ar.id AND ar.is_active = 1
                    {$whereClause}
                    ORDER BY au.created_at DESC
                    LIMIT ? OFFSET ?
                ", array_merge($params, [$limit, $offset]));
                
                // 解析权限
                foreach ($admins as &$admin) {
                    $admin['permissions'] = json_decode($admin['permissions'], true);
                }
                
                // 获取总数
                $total = $db->fetchOne("
                    SELECT COUNT(*) as count 
                    FROM admin_users au
                    JOIN users u ON au.user_id = u.id
                    JOIN admin_roles ar ON au.role_id = ar.id AND ar.is_active = 1
                    {$whereClause}
                ", $params)['count'];
                
                Response::success([
                    'admins' => $admins,
                    'pagination' => [
                        'current_page' => $page,
                        'per_page' => $limit,
                        'total' => (int)$total,
                        'total_pages' => ceil($total / $limit)
                    ]
                ], '获取成功');
                break;
                
            case 'permissions':
                // 获取所有可用权限列表
                $admin = checkAdminPermission('admin.view');
                
                $permissions = [
                    'user' => [
                        'name' => '用户管理',
                        'permissions' => [
                            'user.view' => '查看用户',
                            'user.create' => '创建用户',
                            'user.update' => '更新用户',
                            'user.delete' => '删除用户'
                        ]
                    ],
                    'reservation' => [
                        'name' => '预约管理',
                        'permissions' => [
                            'reservation.view' => '查看预约',
                            'reservation.create' => '创建预约',
                            'reservation.update' => '更新预约',
                            'reservation.delete' => '删除预约'
                        ]
                    ],
                    'activity' => [
                        'name' => '活动管理',
                        'permissions' => [
                            'activity.view' => '查看活动',
                            'activity.create' => '创建活动',
                            'activity.update' => '更新活动',
                            'activity.delete' => '删除活动'
                        ]
                    ],
                    'volunteer' => [
                        'name' => '志愿者管理',
                        'permissions' => [
                            'volunteer.view' => '查看志愿者',
                            'volunteer.create' => '创建志愿者',
                            'volunteer.update' => '更新志愿者',
                            'volunteer.delete' => '删除志愿者'
                        ]
                    ],
                    'team' => [
                        'name' => '团队预约管理',
                        'permissions' => [
                            'team.view' => '查看团队预约',
                            'team.create' => '创建团队预约',
                            'team.update' => '更新团队预约',
                            'team.delete' => '删除团队预约'
                        ]
                    ],
                    'config' => [
                        'name' => '系统配置',
                        'permissions' => [
                            'config.view' => '查看配置',
                            'config.update' => '更新配置'
                        ]
                    ],
                    'schedule' => [
                        'name' => '时间管理',
                        'permissions' => [
                            'schedule.view' => '查看时间设置',
                            'schedule.update' => '更新时间设置'
                        ]
                    ],
                    'closure' => [
                        'name' => '闭馆管理',
                        'permissions' => [
                            'closure.view' => '查看闭馆设置',
                            'closure.create' => '创建闭馆设置',
                            'closure.update' => '更新闭馆设置',
                            'closure.delete' => '删除闭馆设置'
                        ]
                    ],
                    'admin' => [
                        'name' => '管理员管理',
                        'permissions' => [
                            'admin.view' => '查看管理员',
                            'admin.create' => '创建管理员',
                            'admin.update' => '更新管理员',
                            'admin.delete' => '删除管理员'
                        ]
                    ],
                    'statistics' => [
                        'name' => '统计报表',
                        'permissions' => [
                            'statistics.view' => '查看统计'
                        ]
                    ]
                ];
                
                Response::success($permissions, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        $admin = checkAdminPermission('admin.create');
        
        switch ($action) {
            case 'create_role':
                // 创建角色
                if (!isset($input['role_name']) || !isset($input['role_code']) || !isset($input['permissions'])) {
                    Response::error('缺少必要参数');
                }
                
                $roleName = $input['role_name'];
                $roleCode = $input['role_code'];
                $description = $input['description'] ?? '';
                $permissions = $input['permissions'];
                
                // 检查角色代码是否已存在
                $existingRole = $db->fetchOne("SELECT id FROM admin_roles WHERE role_code = ?", [$roleCode]);
                if ($existingRole) {
                    Response::error('角色代码已存在');
                }
                
                // 验证权限格式
                if (!is_array($permissions)) {
                    Response::error('权限格式错误');
                }
                
                $roleId = $db->insert('admin_roles', [
                    'role_name' => $roleName,
                    'role_code' => $roleCode,
                    'description' => $description,
                    'permissions' => json_encode($permissions),
                    'is_active' => 1
                ]);
                
                if ($roleId) {
                    Response::success(['role_id' => $roleId], '创建成功');
                } else {
                    Response::error('创建失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'PUT':
        $admin = checkAdminPermission('admin.update');
        
        switch ($action) {
            case 'update_role':
                // 更新角色
                if (!isset($input['role_id'])) {
                    Response::error('缺少角色ID');
                }
                
                $roleId = (int)$input['role_id'];
                $updateData = [];
                
                if (isset($input['role_name'])) $updateData['role_name'] = $input['role_name'];
                if (isset($input['description'])) $updateData['description'] = $input['description'];
                if (isset($input['permissions'])) {
                    if (!is_array($input['permissions'])) {
                        Response::error('权限格式错误');
                    }
                    $updateData['permissions'] = json_encode($input['permissions']);
                }
                if (isset($input['is_active'])) $updateData['is_active'] = (int)$input['is_active'];
                
                $updateData['updated_at'] = date('Y-m-d H:i:s');
                
                $result = $db->update('admin_roles', $updateData, 'id = ?', [$roleId]);
                
                if ($result) {
                    Response::success(['role_id' => $roleId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'update_admin_role':
                // 更新管理员角色
                if (!isset($input['admin_user_id']) || !isset($input['role_id'])) {
                    Response::error('缺少必要参数');
                }
                
                $adminUserId = (int)$input['admin_user_id'];
                $roleId = (int)$input['role_id'];
                
                // 检查角色是否存在
                $role = $db->fetchOne("SELECT * FROM admin_roles WHERE id = ? AND is_active = 1", [$roleId]);
                if (!$role) {
                    Response::error('角色不存在或未启用');
                }
                
                $result = $db->update('admin_users', [
                    'role_id' => $roleId,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$adminUserId]);
                
                if ($result) {
                    Response::success(['admin_user_id' => $adminUserId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'toggle_admin_status':
                // 启用/禁用管理员
                if (!isset($input['admin_user_id']) || !isset($input['is_active'])) {
                    Response::error('缺少必要参数');
                }
                
                $adminUserId = (int)$input['admin_user_id'];
                $isActive = (int)$input['is_active'];
                
                $result = $db->update('admin_users', [
                    'is_active' => $isActive,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$adminUserId]);
                
                if ($result) {
                    Response::success(['admin_user_id' => $adminUserId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        $admin = checkAdminPermission('admin.delete');
        
        switch ($action) {
            case 'delete_role':
                // 删除角色
                $roleId = (int)($_GET['id'] ?? 0);
                if (!$roleId) {
                    Response::error('缺少角色ID');
                }
                
                // 检查是否有管理员使用此角色
                $adminCount = $db->fetchOne("SELECT COUNT(*) as count FROM admin_users WHERE role_id = ? AND is_active = 1", [$roleId])['count'];
                if ($adminCount > 0) {
                    Response::error('有管理员正在使用此角色，无法删除');
                }
                
                $result = $db->update('admin_roles', [
                    'is_active' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$roleId]);
                
                if ($result) {
                    Response::success(['role_id' => $roleId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            case 'remove_admin':
                // 移除管理员
                $adminUserId = (int)($_GET['id'] ?? 0);
                if (!$adminUserId) {
                    Response::error('缺少管理员ID');
                }
                
                $result = $db->update('admin_users', [
                    'is_active' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$adminUserId]);
                
                if ($result) {
                    Response::success(['admin_user_id' => $adminUserId], '移除成功');
                } else {
                    Response::error('移除失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>